import { getToken } from '@/utils/auth'

export function previewFile(url) {
  const { saveFile } = uni.getFileSystemManager()
  const token = getToken()
  uni.showLoading({
    title: '文件加载中...'
  })
  uni
    .downloadFile({
      url,
      header: {
        token
      },
      timeout: 230000
    })
    .then(data => {
      const fileExtension = data.tempFilePath.substring(data.tempFilePath.lastIndexOf('.') + 1)
      const imageExtension = ['png', 'jpeg', 'jpg']
      const otherExtension = ['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx']
      if (![...imageExtension, ...otherExtension].includes(fileExtension)) {
        uni.showToast({
          icon: 'error',
          duration: 2000,
          title: '无法预览该格式'
        })
      }
      if (data?.statusCode === 200) {
        saveFile({
          tempFilePath: data.tempFilePath,
          success(res) {
            const filePath = res.savedFilePath
            if (imageExtension.includes(fileExtension)) {
              uni.previewImage({
                urls: [filePath]
              })
            }
            if (otherExtension.includes(fileExtension)) {
              uni.openDocument({
                filePath: filePath,
                showMenu: true,
                success: function (res) {
                  console.log('打开文档成功')
                },
                fail: function (error) {
                  console.log(error)
                }
              })
            }
          }
        })
      }
    })
    .catch(err => {
      uni.showToast({
        icon: 'error',
        duration: 2000,
        title: err
      })
    })
    .finally(() => {
      uni.hideLoading()
    })
}
